package zhenbang
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.ActivityEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.StatusEvent;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.net.FileReference;
	import flash.system.Capabilities;
	import flash.utils.ByteArray;
	import flash.utils.clearTimeout;
	CONFIG::NOT_LINUX
	{
		import flash.events.PermissionEvent;
		import flash.permissions.PermissionStatus;
	}
	
	public class MyCam extends Sprite
	{
		private static var mains:MyCam;
		
		public static function get main():MyCam
		{
			if (mains == null)
				mains = new MyCam();
			return mains;
		}
		
		static public const FLV_FRAMERATE:int = 10;
		public static var video:Video = null;
		private static var camera:Camera = null;
		
		public function MyCam()
		{
			if (mains)
				return;
			mains = this;
			mouseChildren = false;
		}
		
		private function startCam():void
		{
			if (Camera.isSupported){
				camera = Camera.getCamera();
				if (camera == null){
					logs.adds("no Camera");
					return;
				}
				
				CONFIG::NOT_LINUX
				{
					if (Camera.permissionStatus != PermissionStatus.GRANTED)
					{
						camera.addEventListener(PermissionEvent.PERMISSION_STATUS, permission);
						try
						{
							camera.requestPermission();
						}
						catch (e:Error)
						{
							// another request is in progress
							logs.adds(e);
						}
					}
					else
					{
						connectCamera();
					}
					return;
				}
				connectCamera();
			}
			else
			{
				logs.adds("Camera is not support");
			}
		}
		
		CONFIG::NOT_LINUX
		{
			private function permission(e:PermissionEvent):void
			{
				if (e.status == PermissionStatus.GRANTED)
				{
					connectCamera();
				}
				else
				{
					// permission denied
					logs.adds("permission denied");
				}
			}
		}
		
		private function connectCamera():void
		{
			var OUTPUT_WIDTH:int = CameraPage.cameraW;
			var OUTPUT_HEIGHT:int = CameraPage.cameraH;
			camera.setMode(OUTPUT_WIDTH, OUTPUT_HEIGHT, FLV_FRAMERATE);
			//camera.setQuality(0, 100);
			
			//video = new Video(OUTPUT_WIDTH, OUTPUT_HEIGHT);
			video = new Video(OUTPUT_WIDTH, OUTPUT_HEIGHT);
			//video.width = OUTPUT_WIDTH;
			//video.height = OUTPUT_HEIGHT;
			video.attachCamera(camera);
			addChild(video);
			video.visible = true;
			logs.adds("Camera started");
		}
		
		public function start_photo(e:Event = null):void
		{
			visible = true;
			if (video){
				video.visible = true;
				addChild(video);
			}else{
				startCam();
			}
		}
		
	}
}

